package com.edou.cms.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.edou.base.page.PageResult;
import com.edou.cms.dao.ICmsArticleDao;
import com.edou.cms.dao.ICmsArticleTagDao;
import com.edou.cms.dao.ICmsTagDao;
import com.edou.cms.dto.CmsArticleTagCondition;
import com.edou.cms.entity.CmsArticleTag;
import com.edou.cms.service.ICmsArticleTagService;

@Service("cmsArticleTagServiceImpl")
@Transactional(value = "transactionManager")
public class CmsArticleTagServiceImpl implements ICmsArticleTagService{

	@Resource(name = "cmsArticleTagDaoImpl")
	private ICmsArticleTagDao cmsArticleTagDao;
	@Resource(name = "cmsTagDaoImpl")
	private ICmsTagDao cmsTagDao;
	@Resource(name = "cmsArticleDaoImpl")
	private ICmsArticleDao cmsArticleDao;
	/**
	 * 分页查询
	 * @param pageResult 分页对象
	 * @param condition 查询条件类
	 */
	public void listCmsArticleTagByPage(PageResult<CmsArticleTag> pageResult,CmsArticleTagCondition condition){
		int rows = cmsArticleTagDao.listCmsArticleTagByPageCount(condition);
		pageResult.setRows(rows);

		RowBounds rowBounds = new RowBounds(pageResult.getCurrentPageIndex(),pageResult.getPageSize());
		List<CmsArticleTag> list = cmsArticleTagDao.listCmsArticleTagByPage(rowBounds,condition);
		pageResult.setResult(list);
	}

	/**
	 * 根据ID查询
	 * @param id 主键
	 * @return 文章标签关联表
	 */
	public CmsArticleTag getCmsArticleTagById(String id){
		return cmsArticleTagDao.getCmsArticleTagById(id);
	}

	/**
	 * 新增
	 * @param item 文章标签关联表
	 */
	public void add(CmsArticleTag item){
		cmsArticleTagDao.add(item);
	}

	/**
	 * 修改
	 * @param item 文章标签关联表
	 */
	public void update(CmsArticleTag item){
		cmsArticleTagDao.update(item);
	}

	/**
	 * 根据ID集合批量删除
	 * @param ids ID集合
	 */
	public void delByIds(String[] ids){
		for (String tagId : ids) {
			CmsArticleTag cmsArticleTagById = cmsArticleTagDao.getCmsArticleTagById(tagId);
			cmsTagDao.updateCmsTagArticle(cmsArticleTagById.getTagId(), "jx");
		}
		cmsArticleTagDao.delByIds(ids);
	}
	
	/**
	 * 保存文章与标签的关联关系
	 * @param articleIds
	 * @param tagId
	 */
	public void saveTagArticle(String[] articleIds, String tagId) {
		//先保存关联关系
		for (String articleId : articleIds) {
			CmsArticleTag articleTag = new CmsArticleTag();
			articleTag.setTagId(tagId);
			articleTag.setArticleId(articleId);
			articleTag.setDeleteFlag(0);
			cmsArticleTagDao.add(articleTag);
			//修改标签文章数量
			cmsTagDao.updateCmsTagArticle(tagId, "zj");
		}	
	}

	@Override
	public List<CmsArticleTag> listCmsArticleTagByArticleId(String articleId) {
		return cmsArticleTagDao.listCmsArticleTagByArticleId(articleId);
	}

	@Override
	public void updateSort(CmsArticleTagCondition condition) {
		cmsArticleDao.updateSort(condition);
	}

}

